package com.hy.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hy.common.Result;
import com.hy.entity.Points;
import com.hy.mapper.PointsMapper;
import com.hy.service.PointsService;
import com.hy.util.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Calendar;
import java.util.Date;


@Service
public class PointsServiceImpl extends ServiceImpl<PointsMapper, Points> implements PointsService {

    @Autowired
    private UserUtil userUtil;

    @Override
    public Result<Boolean> userAddRecords() {
        // 获取用户的ID
        Integer userIdFromToken = userUtil.getUserIdFromToken();

        // 查看今天用户是否已经打卡了
        synchronized (this) {
            // 获取当天0点和23:59:59
            Date now = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(now);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            Date startOfDay = calendar.getTime();

            calendar.set(Calendar.HOUR_OF_DAY, 23);
            calendar.set(Calendar.MINUTE, 59);
            calendar.set(Calendar.SECOND, 59);
            calendar.set(Calendar.MILLISECOND, 999);
            Date endOfDay = calendar.getTime();

            // 查询当天是否已打卡
            long count = lambdaQuery()
                    .eq(Points::getUserId, userIdFromToken)
                    .eq(Points::getDeleteFlag, 0)
                    .between(Points::getRecordTime, startOfDay, endOfDay)
                    .count();

            if (count > 0) {
                return Result.error("今日已打卡，请勿重复打卡！");
            }
        }

        // 打卡参数设置
        Date date = new Date();
        Points points = new Points();
        points.setCreateTime(date);
        points.setUpdateTime(date);
        points.setRecordTime(date);
        points.setDeleteFlag(0);
        // 目前为20积分一天
        points.setPointsNumbers(20L);
        points.setUserId(userIdFromToken);
        save(points);

        return Result.success(Boolean.TRUE);
    }
}